package com.xxxx.server.task;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.xxxx.server.pojo.Employee;
import com.xxxx.server.pojo.MailConstants;
import com.xxxx.server.pojo.MailLog;
import com.xxxx.server.service.IEmployeeService;
import com.xxxx.server.service.IMailLogService;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;

@Component
public class MailTask {
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private IMailLogService mailLogService;
    @Autowired
    private IEmployeeService employeeService;

    //每十秒发送一次
    @Scheduled(cron = "0/10 * * * * ?")
    public void mailTask() {
        //查询消息状态为0且重试时间小于当前时间的消息，只有满足这个条件的消息才需要重新发送
        List<MailLog> mailLogList = mailLogService.list(new QueryWrapper<MailLog>()
                .eq("status", 0)
                .lt("tryTime", LocalDateTime.now()));
        //重试次数超过3次，更新为投递失败，不再重试（status更新为2）
        mailLogList.forEach(mailLog -> {
            if (3 <= mailLog.getCount()) {
                mailLogService.update(new UpdateWrapper<MailLog>().set("status", 2)
                        .eq("msgId", mailLog.getMsgId()));
            }
            //更新重试次数，更新时间，重试时间
            mailLogService.update(new UpdateWrapper<MailLog>()
                    //一分钟更新一次
                    .set("count", mailLog.getCount() + 1)
                    .set("updateTime", LocalDateTime.now())
                    .set("tryTime", LocalDateTime.now().plusMinutes(MailConstants.MSG_TIMEOUT))
                    .eq("msgId", mailLog.getMsgId()));

            //获取发送的消息中的employee信息
            Employee employee = employeeService.getEmployee(mailLog.getEid()).get(0);
            //发送消息
            rabbitTemplate.convertAndSend(MailConstants.MAIL_EXCHANGE_NAME,
                    MailConstants.MAIL_ROUTING_KEY_NAME, employee,
                    new CorrelationData(mailLog.getMsgId()));
        });
    }
}
